﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Web;
using System.Text.RegularExpressions;
using System.Windows.Forms;

/// <summary>
/// 扫码枪类
/// </summary>
public class Scaner
{

    /// <summary>
    /// 发布器委托
    /// </summary>
    /// <param name="Barcode">条码字符串</param>
    public delegate void ScanerDelegate(string Barcode);

    /// <summary>
    /// 接收到有效条码的事件
    /// </summary>
    public event ScanerDelegate ScanerReceived;

    /// <summary>
    /// 条码字符串
    /// </summary>
    public string BarCode { get; set; }

    /// <summary>
    /// 按键输入字符list
    /// </summary>
    public List<Keys> InputKeys { get; set; }
    
    public Scaner()
    {
        BarCode = "";
        InputKeys = new List<Keys>();
    }
    
    /// <summary>
    /// 处理一个捕获的按键键值，如果扫码完毕，触发接收事件ScanerReceived
    /// </summary>
    /// <param name="key">按键键值</param>
    public void Add(Keys key)
    {
        //忽略扫码枪传来的Shift键值
        if (key == Keys.ShiftKey)
        {
            return;
        }
        InputKeys.Add(key);

        //扫描以回车为结束符 霍尼韦尔可扫描设置回车结束
        if (InputKeys[InputKeys.Count - 1] == Keys.Enter)
        {
            BarCode = "";
            for (int i = 0; i < InputKeys.Count; i++)
            {
                BarCode += Convert.ToChar(InputKeys[i]);
            }
            InputKeys.Clear();
            
            if (!string.IsNullOrEmpty(BarCode))//触发事件
            {
                ScanerReceived(BarCode);
            }
        }
    }
}
